package com.CmJava.servlet.handlerAdapter;

import com.CmJava.servlet.executionChain.handlerMethodMapping.HandlerMethod;
import com.CmJava.servlet.modelAndView.ModelAndView;
import com.CmJava.servlet.modelAndView.ModelAndViewContainer;
import com.CmJava.servlet.modelAndView.ModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Controller的对应映射的执行器
 */
public class RequestMappingHandlerAdapter implements HandlerAdapter {
    @Override
    public boolean support(Object handler) {
        return handler instanceof HandlerMethod && this.supportsInternal((HandlerMethod) handler);
    }

    @Override
    public ModelAndView handle(HttpServletRequest processedRequest, HttpServletResponse response, Object handler) {
        return this.handleInternal(processedRequest, response, (HandlerMethod) handler);
    }

    private ModelAndView handleInternal(HttpServletRequest processedRequest, HttpServletResponse response, HandlerMethod handler) {

        ModelAndView mav = this.invokeHandlerMethod(processedRequest, response, handler);
        return mav;
    }

    private ModelAndView invokeHandlerMethod(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) {

        ServletInvocableHandlerMethod invocableMethod = this.createInvocableHandlerMethod(handlerMethod);
        ModelAndViewContainer mavContainer = new ModelAndViewContainer();
        invocableMethod.invokeAndHandle(request,response, mavContainer, new Object[0]);
        ModelAndView modelAndView = this.getModelAndView(mavContainer, request,response);
        return modelAndView;

    }

    private ModelAndView getModelAndView(ModelAndViewContainer mavContainer, HttpServletRequest request, HttpServletResponse response) {

        ModelMap model = mavContainer.getModel();
        ModelAndView mav=null;
        if (mavContainer.getViewName()!=null){
            mav = new ModelAndView(mavContainer.getViewName(), model);
        }
        return mav;
    }

    private ServletInvocableHandlerMethod createInvocableHandlerMethod(HandlerMethod handlerMethod) {
        return new ServletInvocableHandlerMethod(handlerMethod);
    }

    /**
     * RequestMappingHandlerAdapter就是处理@Controller类型的请求的
     *
     * @param handler
     * @return
     */
    private boolean supportsInternal(HandlerMethod handler) {
        return true;
    }
}
